package com.endoc.agingtools;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.endoc.agingtools.adapter.DeviceRecycleViewAdapter;
import com.endoc.agingtools.adapter.KaweiRecycleViewAdapter;
import com.endoc.agingtools.inteface.IregisterAdapter;
import com.endoc.agingtools.litepal.BindDevice;
import com.endoc.agingtools.utils.BleUtils;
import com.endoc.agingtools.utils.ToastUtils;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.callback.BleScanCallback;
import cn.com.heaton.blelibrary.ble.model.BleDevice;
import pub.devrel.easypermissions.EasyPermissions;

import static cn.com.heaton.blelibrary.ble.Ble.REQUEST_ENABLE_BT;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks, View.OnClickListener, IregisterAdapter {
    String TAG = "agingTool";
    Activity mActivity = this;
    private static final String[] BLE = {Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION};
    private static final int RC_LOCATION_GPS_PREM = 124;
    List<BleDevice> searchValue = new ArrayList<BleDevice>();//搜索到的蓝牙设备
    List<BleDevice> mBindDevice = new ArrayList<BleDevice>();//需要进行绑定的蓝牙设备
    private RecyclerView rcDevice;
    RecyclerView.Adapter mDeviceRecycleViewAdapter;
    List<ItemBean> itemBeanList = new ArrayList<>();
    private List<BindDevice> mBindDevices;//已经绑定的设备列表
    private KaweiRecycleViewAdapter mKaweiRecycleViewAdapter;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_start:
                //给绑定的设备并且已经连接的设备发送启动命令
                BleUtils.sendStartCmd();
                break;
            case R.id.bt_end:
                //给绑定的设备并且已经连接的设备发送停止命令
                BleUtils.sendEndCmd();
                break;
            case R.id.bt_confirm:
                startActivity(new Intent(mActivity, SystemSettingActivity.class));
                break;
            case R.id.et_confirm_max_min:
                //如果最高最低值为空,那么就提示
                if (etMax.getText().toString().trim().isEmpty() || etMin.getText().toString().trim().isEmpty()) {
                    ToastUtils.showToast(mActivity, "没有设置最大值或者最小值");
                } else {
                    //将最大值和最小值整理起来
                    //查询当前绑定的设备
                    ContentValues contentValues = new ContentValues();
                    contentValues.put("max", etMax.getText().toString().trim());
                    contentValues.put("min", etMin.getText().toString().trim());
                    LitePal.updateAll(BindDevice.class, contentValues, "isUser = ?", "1");
                }
                break;
            default:
                break;
        }
    }

    private EditText etMin;
    private EditText etMax;

    private Button btCreateBd;

    public void initData() {
        for (int i = 1; i < 6; i++) {
            ItemBean itemBean = new ItemBean();
            itemBean.kaiwei = i;
            itemBeanList.add(itemBean);
        }
        //查找当前数据库中已经绑定的设备
        mBindDevices = LitePal.where("isUser = ?", "1").find(BindDevice.class);
        Log.d(TAG,"数据库绑定数据长度="+mBindDevices.size());
        //设置itemBean的值
        for (int i = 0; i < mBindDevices.size(); i++) {
            itemBeanList.get(mBindDevices.get(i).getKawei() - 1).deviceName = mBindDevices.get(i).getDeviceName();
        }
    }


    public void initView() {
        rcDevice = (RecyclerView) findViewById(R.id.rc_device);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rcDevice.setLayoutManager(manager);
        /*mDeviceRecycleViewAdapter= new DeviceRecycleViewAdapter(this,value,mBindDevice,rcDevice);
        rcDevice.setAdapter(mDeviceRecycleViewAdapter);*/
        //当前
        mKaweiRecycleViewAdapter = new KaweiRecycleViewAdapter(mActivity, itemBeanList, searchValue, rcDevice);
        rcDevice.setAdapter(mKaweiRecycleViewAdapter);

        findViewById(R.id.bt_confirm).setOnClickListener(this);
        findViewById(R.id.bt_start).setOnClickListener(this);
        findViewById(R.id.bt_end).setOnClickListener(this);
        findViewById(R.id.et_confirm_max_min).setOnClickListener(this);
        etMin = (EditText) findViewById(R.id.et_min);
        etMax = (EditText) findViewById(R.id.et_max);
        btCreateBd = (Button) findViewById(R.id.bt_create_bd);
    }

    public boolean containDevice(String name) {
        for (int i = 0; i < mBindDevices.size(); i++) {
            if (name.equals(mBindDevices.get(i).getDeviceName())) {
                return true;
            }
        }
        return false;
    }

    public void startSearch() {
        if (EasyPermissions.hasPermissions(mActivity, BLE)) {
            LitePal.getDatabase();//初始化数据库
            //开始搜索
            Ble.getInstance().startScan(new BleScanCallback<BleDevice>() {
                @Override
                public void onLeScan(BleDevice device, int rssi, byte[] scanRecord) {

                    synchronized (MainActivity.class) {
                        if (device.getBleName() != null && device.getBleName().contains("Endoc_")) {
                            if (searchValue.size() == 0) {//如果一个都没有,那么直接添加
                                searchValue.add(device);
                                if (containDevice(device.getBleName())) {//如果绑定了此设备,那么就直接连接
                                    BleUtils.connectDevice(device, mKaweiRecycleViewAdapter,mDeviceRecycleViewAdapter,null);
                                }
                                //然后更新ui
                                if (mDeviceRecycleViewAdapter != null) {//如果注册了设置列表界面,那么才更新
                                    mDeviceRecycleViewAdapter.notifyDataSetChanged();
                                }
                                return;
                            }
                            //查看是否包含此设备
                            for (int i = 0; i < searchValue.size(); i++) {
                                if (searchValue.get(i).getBleName().equals(device.getBleName())) {
                                    return;
                                }
                            }
                            //如果设备集合大于5,那么就不添加到集合中去了
                            /*if(value.size()>5){
                                return;
                            }*/
                            //如果不包含此设备,那么就添加
                            searchValue.add(device);
                            if (containDevice(device.getBleName())) {//如果绑定了此设备,那么就直接连接
                                BleUtils.connectDevice(device, mKaweiRecycleViewAdapter, mDeviceRecycleViewAdapter,null);
                            }
                            if (mDeviceRecycleViewAdapter != null) {
                                mDeviceRecycleViewAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                }
            });
        } else {
            EasyPermissions.requestPermissions(MainActivity.this,
                    "权限拒绝,请开启权限",//使用官方提供的弹窗(`AppSettingsDialog`)的时候会用到这个字符串,作为用户拒绝之后弹窗的内容
                    RC_LOCATION_GPS_PREM,
                    BLE);
        }
    }


    /*检查蓝牙是否支持及打开*/
    private void checkBle() {
        Log.d(TAG, "checkBle");
        // 检查设备是否支持BLE4.0

        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        // 初始化蓝牙适配器. API版本必须是18以上, 通过 BluetoothManager 获取到BLE的适配器.

        // 检查当前的蓝牙设别是否支持.
        if (adapter == null) {
            Toast.makeText(mActivity, "不支持Ble蓝牙", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!adapter.isEnabled()) {
            Log.d(TAG, "checkBle提示打开蓝牙");
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        } else {
            startSearch();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LitePal.initialize(this);
        initData();
        initView();
        checkBle();
        //LitePal.getDatabase();//初始化数据库
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(FinalStaticString.TAG, "onDestroy");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //Log.d(TAG,"Activity.RESULT_OK");
        if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) {
            startSearch();
        } else if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
            finish();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //将结果交由EasyPermissions解决
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsGranted");
        if (requestCode == RC_LOCATION_GPS_PREM) {
            LitePal.getDatabase();//初始化数据库
            startSearch();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }


    @Override
    public void register(RecyclerView.Adapter adapter) {
        mDeviceRecycleViewAdapter = adapter;
    }

    //屏蔽返回键
    //重写系统自带的返回键功能
    @Override
    public void onBackPressed() {
        //将super.onBackPressed();注释掉
//       super.onBackPressed();
        moveTaskToBack(true);//设置为home键功能
    }
}
